package com.xzy.shop.web.servlet;

import com.xzy.shop.domain.Admin;
import com.xzy.shop.domain.ResultInfo;
import com.xzy.shop.domain.User;
import com.xzy.shop.service.UserService;
import com.xzy.shop.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
    private UserService service = new UserServiceImpl();

    public void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //校验码校验
        String check = request.getParameter("check");
        //从session中获取验证码
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");

        //保证验证码只能使用一次
        session.removeAttribute("CHECKCODE_SERVER");

        if (checkcode_server == null || !checkcode_server.equalsIgnoreCase(check)) {
            //验证码错误
            ResultInfo info = new ResultInfo();
            //注册失败
            info.setFlag(false);
            info.setErrorMsg("验证码错误！");
            //将info对象序列化为json
            String json = writeValueAsStream(info, response);
            //将json数据写回客户端
            //设置context-type
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return;
        }

        String check_pwd = request.getParameter("check_pwd");
        String password = request.getParameter("password");

        if (!check_pwd.equals(password)) {
            //两次密码输入不一致
            ResultInfo info = new ResultInfo();
            //注册失败
            info.setFlag(false);
            info.setErrorMsg("两次输入密码不一致！");
            //将info对象序列化为json
            String json = writeValueAsStream(info, response);
            //将json数据写回客户端
            //设置context-type
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return;
        }

        //1. 获取数据
        Map<String, String[]> map = request.getParameterMap();

        //2. 封装对象
        User user = new User();
        try {
            BeanUtils.populate(user, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //3. 调用service完成注册
        boolean flag = service.regist(user);
        ResultInfo info = new ResultInfo();
        //4.响应结果
        if (flag) {
            info.setFlag(true);
        } else {
            info.setFlag(false);
            info.setErrorMsg("注册失败！");
        }
        String json = writeValueAsStream(info, response);
        //将json数据写回客户端
        //设置content-type
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
    }

    /**
     * 用户激活
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void active(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取激活码
        String code = request.getParameter("code");

        if (code != null) {
            //调用service完成激活
            boolean flag = service.active(code);

            //判断标记
            String msg = null;
            if (flag) {
                //激活成功
                msg = "激活成功，请<a href='http://localhost:8080/javaweb_shop/index.html'>登录</a>";
            } else {
                //激活失败
                msg = "激活失败, 请联系管理员";
            }
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(msg);
        }
    }

    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        //1. 获取对象
        Map<String, String[]> map = request.getParameterMap();

        //2. 封装对象
        User user = new User();
        try {
            BeanUtils.populate(user, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //3. 进行验证登录
        ResultInfo info = new ResultInfo();

        boolean status = service.checkStatus(user);
        if (status == false) {
            info.setFlag(false);
            info.setErrorMsg("您还未激活，请前往邮箱激活!");
        } else {
            User loginUser = service.check(user);
            if (loginUser == null) {
                info.setFlag(false);
                info.setErrorMsg("用户名或密码错误");
            } else {
                info.setFlag(true);
                session.setAttribute("loginUser", loginUser);
            }
        }
        String json = writeValueAsStream(info, response);

        //将json数据写回客户端
        //设置content-type
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
    }

    public void findOne(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("loginUser");
        writeValue(user, response);
    }

    public void exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //销毁session
        request.getSession().invalidate();
        //2. 跳转登录页面
        response.sendRedirect(request.getContextPath() + "/index.html");
    }

    public void saveInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //已登录用户
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        Map<String, String[]> infos = request.getParameterMap();
        User user = service.addInfo(loginUser, infos);
        writeValue(user, response);
    }

    public void adminLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("pwd");
        Admin admin = service.adminLogin(username, password);

        writeValue(admin, response);
    }

    public void findAllUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<User> list = service.findAllUser();
        writeValue(list, response);
    }
}
